package testJdk.base.juc_test.test_atomic;

import org.junit.Test;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @ClassName : learn_jdk.base.juc_test.test_atomic.TestAtomicDemo
 * @Description : 类描述
 * Created by cyd on 2021-10-22 10:28:48
 */
public class TestAtomicDemo {

    @Test
    public void test01() {
        AtomicDemo atomicDemo = new AtomicDemo();

        for (int i = 0; i < 10; i++) {
            new Thread(atomicDemo).start();
        }
    }

    @Test
    public void test02() {
        AtomicDemo2 atomicDemo2 = new AtomicDemo2();

        for (int i = 0; i < 10; i++) {
            new Thread(atomicDemo2).start();
        }
    }

}


class AtomicDemo implements Runnable {

    private volatile int serialNumber = 0;

    @Override
    public void run() {
//        try {
//            Thread.sleep(200);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        System.out.println(Thread.currentThread().getName() + ":" + getSerialNumber());
    }

    public synchronized int getSerialNumber() {
        return serialNumber++;
    }
}

class AtomicDemo2 implements Runnable {

    // 和包装类的使用一样
    private AtomicInteger serialNumber = new AtomicInteger(0);

    @Override
    public void run() {
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + ":" + getSerialNumber());
    }

    public int getSerialNumber() {
        // 相当于原来的serialNumber++
        return serialNumber.getAndIncrement();
    }
}